package com.logicwin.aibala.services.file;

import com.logicwin.aibala.com.GlobalConfig;
import com.logicwin.aibala.services.net.NetConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageManager {
	private ImageManager() {
	}

	public static Bitmap getImageFromCache(String imagePath) {
		Bitmap ret = FileCache.Instance().get(imagePath);
		return ret;
	}

	public static Bitmap getImageFromNet(String imagePath) {

		Bitmap image = getImageFromCache(imagePath);
		if (image != null)
			return image;
		else {
			String fileName = FileConnection.getCurrentPath() + "/"
					+ imagePath.replace("/", "").replace(":", "");
                        image = BitmapFactory.decodeFile(fileName);
			if (image != null){
				FileCache.Instance().put(imagePath, image);
				return image;
			}
			else {
				NetConnection.downLoadFile(imagePath, fileName);
				image = BitmapFactory.decodeFile(fileName);
				
				if (image != null) {
					//if (image.getWidth() * image.getHeight() < 200 * 200)
					FileCache.Instance().put(imagePath, image);
					return image;
				} else {
					return null;
				}
			}
		}
	}
	
	
	private static ImageMemCache<String, Bitmap> iconMemCache = new ImageMemCache<String, Bitmap>(100);
	private static ImageFileCache iconFileCache = new ImageFileCache(100);
	
	public static Bitmap getIconImageQuick(String imgurl) {
		return iconMemCache.get(imgurl);
	}
	
	/**
	 * 获取图标位图对象（阻塞操作，放在异步处理流程中）
	 * @param imgurl
	 * @return
	 */
	public static Bitmap getIconImage(String imgurl) {
		Bitmap ret = iconMemCache.get(imgurl);
		if(null == ret) {
			String filepath = iconFileCache.get(imgurl);
			if(null == filepath) {
				filepath = GlobalConfig.getIMGCacheDir() + "/" + imgurl.replace(":", "").replace("/", "");
				if(NetConnection.downLoadFile(imgurl, filepath)) {
					iconFileCache.put(imgurl, filepath);
				}
				else {
					return null;
				}
			}
			ret = BitmapFactory.decodeFile(filepath);
			iconMemCache.put(imgurl, ret);
		}
		
		return ret;
	}
	
	private static ImageMemCache<String, Bitmap> detailImgMemCache = new ImageMemCache<String, Bitmap>(10);
	private static ImageFileCache detailImgFileCache = new ImageFileCache(20);
    
	public static Bitmap getDetailImageQuick(String imgurl) {
		return detailImgMemCache.get(imgurl);
	}
	
	/**
	 * 获取详细信息图对象（阻塞操作，放在异步处理流程中）
	 * @param imgurl
	 * @return
	 */
	public static Bitmap getDetailImage(String imgurl) {
		Bitmap ret = detailImgMemCache.get(imgurl);
		if(null == ret) {
			String filepath = iconFileCache.get(imgurl);
			if(null == filepath) {
				filepath = GlobalConfig.getIMGCacheDir() + "/" + imgurl.replace(":", "").replace("/", "");
				if(NetConnection.downLoadFile(imgurl, filepath)) {
					detailImgFileCache.put(imgurl, filepath);
				}
				else {
					return null;
				}
			}
			ret = BitmapFactory.decodeFile(filepath);
			detailImgMemCache.put(imgurl, ret);
		}
		
		return ret;
	}
}
